from jutils import *

#from ConfigParser import ConfigParser
import json

KA_0 = '0';

class KA:
	def __init__(this, parentKA_ = null):
		this.parentKA = parentKA_;
		this.subKA = null;
		this.state = KA_0;
		this.states = {};
		this._loadActions("ini\KA.ini");
	
	#interface
	def doRequest(this, req):
		res = null;
		if (this.states[this.state].count(req.type) != 0):
			res = this._doRequest(req);
		elif (this.subKA != null):
			res = this.subKA.doRequest(req);
		if (res == null):
			res = req;
		return res;
	
	def setState(this, state_, exitValue_ = null):
		if (this.state == state_):
			return;
		if (this.states.keys().count(state_) == 0):
			raise Exception("KA " + this.name + " havn't state " + state_);
		
		if (state_ == KA_0):
			this.exitValue = exitValue_;
			if (this.parentKA != null):
				this.parentKA._stopSubKA();
		
		this.state = state_;
		
		if (this.subKA != null):
			this.subKA.exit();
			this.subKA = null;
		
		print "KA", this.name, "->", this.state;
	
	def startSubKA(this, KFname_):
		this.subKA = eval(KFname_)(this);
		this.subKA.doState("start");
	
	#
	def _stopSubKA(this):
		this.doState(this.subKA.exitValue);
		this.subKA = null;
	
	#
	def _loadActions(this, fname):
		ini_info = this._loadJSONini(fname)
		this.states = ini_info[this.name]
	
	def _loadJSONini(this, fname):
		f = open(fname);
		res = json.load(f);
		f.close();
		return res;
		
super = KA

